package ktvcmdserver

import (
	"encoding/binary"
	//"fmt"
	"ktvserver/config"
	"ktvserver/core/udpserver"
	"ktvserver/ktvutil"
	"os"
	"path/filepath"
	//"strings"
)

const KTV_SYSTEM_DIRECTORY = 0
const KTV_MAIN_DIRECTORY = 1

// CMD_QUERY_CONFIG
// 查询服务器配置
func KtvQueryConfig(w udpserver.ResponseWriter, req *udpserver.Request) {

	key := ""
	for i := 0; i < 40; i++ {
		if req.CmdMessage.Data[i] == 0 {
			key = string(req.CmdMessage.Data[0:i])
			break
		}
	}

	//

	value := config.GetValue(key, "")

	//fmt.Printf("KtvQueryConfig, len(key)=%d, key=%s, value=%s\n", len(key), key, value)

	var cmd udpserver.KtvCmdMessage
	cmd.Reset()
	binary.Write(w, binary.LittleEndian, &cmd)
	w.WriteString(value)

}

// CMD_GET_KTV_FILE_LEN
// 查询系统文件的大小
func KtvQueryFileLen(w udpserver.ResponseWriter, req *udpserver.Request) {

	totalLen := req.Rd.Len()
	//
	if totalLen <= req.CmdMessage.StructSize() {
		// 不响应信息
		return
	}

	// CMD后的附带信息
	left := totalLen - req.CmdMessage.StructSize()
	textBytes := make([]byte, left+2)
	req.Rd.Seek(int64(req.CmdMessage.StructSize()), 0)
	req.Rd.Read(textBytes)

	// filename 已经是utf8编码的文本
	filename := ktvutil.Utf16ByteToUtf8(textBytes)
	dstfile := ""

	switch req.CmdMessage.Series {
	case KTV_SYSTEM_DIRECTORY:
		// KTV下的SYSTEM系统目录
		dstfile = filepath.Join("SYSTEM", filename)
	case KTV_MAIN_DIRECTORY:
		// KTV目录
		dstfile = filename
	}

	var dataLength uint32

	// 获取文件的信息
	if fi, err := os.Stat(dstfile); err != nil {
		// 找不到文件直接发送空数据
		dataLength = 0
	} else {
		dataLength = uint32(fi.Size())
	}

	//	fmt.Printf("KtvQueryFileLen, filename=%s, length=%d\n", filename, dataLength)

	var cmd udpserver.KtvCmdMessage

	cmd.Reset()
	cmd.ServerID = dataLength

	binary.Write(w, binary.LittleEndian, &cmd)

}

// CMD_GET_KTV_FILE_SHA1
// 查询系统文件的sha1值
func KtvQueryFileSHA1(w udpserver.ResponseWriter, req *udpserver.Request) {

	totalLen := req.Rd.Len()
	//
	if totalLen <= req.CmdMessage.StructSize() {
		// 不响应信息
		return
	}

	// CMD后的附带信息
	left := totalLen - req.CmdMessage.StructSize()
	textBytes := make([]byte, left+2)
	req.Rd.Seek(int64(req.CmdMessage.StructSize()), 0)
	req.Rd.Read(textBytes)

	// filename 已经是utf8编码的文本
	filename := ktvutil.Utf16ByteToUtf8(textBytes)
	dstfile := ""

	switch req.CmdMessage.Series {
	case KTV_SYSTEM_DIRECTORY:
		// KTV下的SYSTEM系统目录
		dstfile = filepath.Join("SYSTEM", filename)
	case KTV_MAIN_DIRECTORY:
		// KTV目录
		dstfile = filename
	}

	var cmd udpserver.KtvCmdMessage
	cmd.Reset()

	// 获取文件的SHA1计算值
	if hash, err := ktvutil.GetFileSha1(dstfile); err == nil {
		for i := 0; i < len(hash); i++ {
			cmd.Data[i] = hash[i]
		}
		//fmt.Printf("KtvQuerySha1, filename=%s, hash=%X\n", filename, hash)
	}

	binary.Write(w, binary.LittleEndian, &cmd)

}
